/**
 * 
 * 公共医嘱项列表
 */
import React from 'react';
import {
    Card, Table, Input, Form, Select, Popconfirm, Col, AutoComplete, Tabs,
    DatePicker, Button, Checkbox, Icon, Divider, message, Modal,
} from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import CommonPagination from 'components/pagination/index';
import store from 'store'
import moment from 'moment';
import './style/index.less';

const { RangePicker } = DatePicker;
const Search = Input.Search;
const Option = Select.Option;
const TabPane = Tabs.TabPane;
const confirm = Modal.confirm;
const FormItem = Form.Item;

class UsageRelatedOrdersPage extends React.Component {
    constructor(props) {
        super(props)
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        var date = new Date()
        this.state = {
            dataSource: [],
            total: 0,
            page: 1,
            pageSize: 20,
            tableTotal: 0,
            tablePage: 1,
            pageRightSize: 10,
            userData: userData,
            size: 'small',
            autoFlag: false,
            startDate: moment(date).format(dayFormat),
            locList: [],
            locType: ''
        }
    }

    componentDidMount() {
        this.loadData(1)
        this.initData()
        this.loadHospitalMsg()//医院
        this.loadAdmType()//就诊类型
        this.getLocSelectData(); // 开单科室
    }

    loadOrdNoteList() {
        var params = {
            params: [{
                findCode: this.state.findCode
            }]
        }
        $http.post('urlDeault', this, {
            code: "01010002",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        ordNoteList: res.result.Data
                    })
                }
            }
        });
    }

    loadAdmType() {
        var params = {
            params: [{}]
        }
        $http.post('urlDeault', this, {
            code: "03050088",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        admType: res.result.Data
                    })
                }
            }
        });
    }

    // 获取登录科室下拉数据
    getLocSelectData = () => {
        let { userData } = this.state;
        var params = {
            params: [{
                hospID: userData && userData.hospID ? userData.hospID : "",
                type: this.state.locType || ''
            }]
        }
        $http.post('urlDeault', this, {
            code: "04020008",
            data: params,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let locList = res.result && res.result.Data && res.result.Data.length > 0 ? res.result.Data : [];
                    this.setState({
                        locList
                    })
                }
            }
        });
    }

    //获取医院信息
    loadHospitalMsg() {
        var params = {
            params: [{
                logonHospID: this.state.userData.hospID,
                logonGroupID: this.state.userData.groupID,
                hospRequired: '1',
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040001",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        hospData: res.depDoctor
                    })
                }
            }
        });
    }


    initData() {
        this.columns = [
            {
                title: '代码',
                dataIndex: 'code',
                width: 100,
                align: 'center',
            },
            {
                title: '描述',
                dataIndex: 'descripts',
                width: 200,
                align: 'left',
            }
        ],
            this.rightColumns = [
                {
                    title: '医院',
                    dataIndex: 'hospDesc',
                    width: 100,
                    align: 'center',
                },
                {
                    title: '开单科室',
                    dataIndex: 'locDesc',
                    width: 100,
                    align: 'center',
                },
                {
                    title: '就诊类型',
                    dataIndex: 'admTypeDesc',
                    width: 100,
                    align: 'center',
                },
                {
                    title: '医嘱项',
                    dataIndex: 'medDesc',
                    width: 100,
                    align: 'center',
                },
                {
                    title: '数量',
                    dataIndex: 'qty',
                    width: 100,
                    align: 'center',
                },
                {
                    title: '自动计算费用',
                    dataIndex: 'autoFlag',
                    width: 100,
                    align: 'center',
                    render(autoFlag) {
                        let config = {
                            'Y': '是',
                            'N': '否'
                        }
                        return config[autoFlag];
                    }
                },
                {
                    title: '生效日期',
                    dataIndex: 'startDate',
                    width: 100,
                    align: 'center',
                },
                {
                    title: '失效日期',
                    dataIndex: 'stopDate',
                    width: 100,
                    align: 'center',
                }, {
                    title: '操作',
                    dataIndex: 'opertion',
                    width: 100,
                    align: 'center',
                    render: (text, data) => {
                        return (
                            <span>
                                <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                                <span className='span' onClick={this.handleEdit.bind(this, data)}>编辑</span>
                                <Divider type="vertical" />
                                <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                                <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.handleDel.bind(this, data)} >
                                    <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                                </Popconfirm>
                            </span >
                        )
                    }
                }
            ]
    }

    handleEdit(data) {
        this.setState({
            hospID: String(data.hospID),
            admTypeID: data.admTypeID,
            medID: data.medID,
            qty: data.qty,
            startDate: data.startDate,
            stopDate: data.stopDate,
            autoFlag: data.autoFlag == 'Y' ? true : false,
            findCode: data.medDesc,
            rowID: data.id,
            locID: data.locID,
        }, () => {
            this.loadOrdNoteList()
            this.props.form.setFieldsValue({
                hospID: String(data.hospID),
                admTypeID: data.admTypeID,
                medID: data.medID,
                qty: data.qty,
                locID: data.locID,
                // startDate: data.startDate ? moment(data.startDate).format(dayFormat) : '',
                // stopDate: data.stopDate ? moment(data.stopDate).format(dayFormat) : '',
                autoFlag: data.autoFlag == 'Y' ? true : false,
                id: data.id
            })
        })
    }

    handleDel(data) {
        var params = {
            params: [{
                logonHospID: this.state.userData.hospID,
                userID: this.state.userData.userID,
                logonGroupID: this.state.userData.groupID,
                id: [data.id]

            }]

        }
        $http.post('urlDeault', this, {
            code: "03010115",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('删除成功')
                    this.loadRightTableData(1)
                }
            }
        });
    }


    loadRightTableData(page, pageSize, e) {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                locID: this.state.userData.locID,
                usageID: this.state.usageID,
                // admTypeID: this.state.admTypeID

            }],
            pagination: [{
                pageSize: this.state.pageRightSize,
                currentPage: page
            }]

        }
        $http.post('urlDeault', this, {
            code: "03010113",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        tableData: res.result.data,
                        tableTotal: res.result.totalCount,
                        tablePage: page,
                        tableSearch: e,
                    });
                }
            }
        });
    }

    loadData(page, pageSize, e) {
        var params = {
            params: [{
                searchCode: this.state.descripts ? this.state.descripts : this.state.searchCode,
                code: this.state.searchCode ? this.state.searchCode : undefined,
                desc: this.state.descripts ? this.state.descripts : undefined,
            }],
            pagination: [{
                pageSize: this.state.pageSize,
                currentPage: page
            }]

        }
        $http.post('urlDeault', this, {
            code: "01040065",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        dataSource: res.result.data,
                        total: res.result.totalCount,
                        usageID: (!Util.isEmpty(res.result) && !Util.isEmpty(res.result.data)) ? res.result.data[0].id : '',
                        page: page,
                        search: e,
                    }, () => {
                        this.loadRightTableData(1)
                    });
                }
            }
        });
    }

    //点击行，渲染当前行样式
    onClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    usageID: record.id,
                }, () => {
                    this.loadRightTableData(1)
                })
            },
        };
    }
    //点击行，渲染当前行样式
    onRightClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    rowID: record.id,
                }, () => {
                    this.handleEdit(record)
                    // this.loadRightTableData(1)
                })
            },
        };
    }

    clearInput() {
        var date = new Date()
        this.props.form.resetFields();
        this.setState({
            hospID: undefined,
            medID: undefined,
            locID: undefined,
            admTypeID: undefined,
            startDate: moment(date).format(dayFormat),
            stopDate: '',
            autoFlag: false,
            qty: undefined,
            rowID: undefined
        })
    }

    //点击行，渲染当前行样式 
    setRowClassName = (record) => {
        return record.id === this.state.usageID ? 'clickRowStyle' : '';
    }
    //点击行，渲染当前行样式 
    setRowRightClassName = (record) => {
        return record.id === this.state.rowID ? 'clickRowStyle' : '';
    }

    //分页切换
    onChange(e) {
        this.setState({ page: e }, () => {
            this.loadData(e);
        });
    }
    //分页切换
    onRightChange(e) {
        this.setState({ tablePage: e }, () => {
            this.loadRightTableData(e);
        });
    }

    //分页切换
    changeRightPageSize(current, pageSize) {
        this.setState({ pageRightSize: pageSize, tablePage: current }, () => {
            this.loadRightTableData(current, pageSize);
        });
    }
    //分页切换
    changePageSize(current, pageSize) {
        this.setState({ pageSize: pageSize, page: current }, () => {
            this.loadData(current, pageSize);
        });
    }

    handleSelectOption(name, e) {
        this.setState({
            [name]: e
        })
    }

    handleSelectChange(name, e) {
        this.setState({
            [name]: e
        }, () => {
            if (e && e.length >= 2) {
                this.loadOrdNoteList(); //医嘱项
            }
        })
    }

    // 按可是类型过滤科室
    handleSelectLocTypeChange(name, e, opt) {
        this.setState({
            [name]: e,
            locType: opt.props.code
        }, () => {
            this.getLocSelectData();    //科室
        })
    }

    changeCommonCheckBox(name, e) {
        this.setState({
            [name]: e.target.checked
        })
    }

    onSubmit() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let params = {
                    params: [{
                        id: values.id || this.state.rowID,
                        userID: this.state.userData.userID,
                        hospID: this.state.userData.hospID,
                        locID: values && values.locID ? values.locID : this.state.userData.locID,
                        usageID: this.state.usageID,
                        qty: values.qty || "",
                        autoFlag: this.state.autoFlag == true ? 'Y' : 'N',
                        startDate: values.startDate ? moment(values.startDate).format('YYYY-MM-DD') : undefined,//生效日期
                        stopDate: values.stopDate ? moment(values.stopDate).format('YYYY-MM-DD') : undefined,//失效日期
                        medID: values.medID || '',
                        admTypeID: values.admTypeID || ''
                    }]
                }
                $http.post('urlS', this, {
                    code: '03010114',
                    data: params,
                    success: function (res) {
                        if (res.errorCode == '0') {
                            message.success('保存成功')
                            this.clearInput()
                            this.loadRightTableData(1)
                        }
                    }
                })

            }
        })
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        var date = new Date()
        const formItemLayout = { // label 和input宽度
            labelCol: { span: 9 },
            wrapperCol: { span: 15 },
        }

        const formItemCheck = {
            labelCol: { span: 16 },
            wrapperCol: { span: 8 },
        }

        //所属医院参数
        let hospitalOption = [];
        this.state.hospData && this.state.hospData.map((item, index) => {
            hospitalOption.push(<Option key={index} value={item.id} name={item.descripts} code={item.descriptsSPCode}>{item.descripts}</Option>)
        })

        //就诊类型
        let admTypeOption = []
        this.state.admType && this.state.admType.map((item, index) => {
            admTypeOption.push(<Option key={index} value={item.admTypeID} code={item.admCode} >{item.admDesc}</Option>)
        })

        //医嘱项
        let ordNoteListtOption = []
        this.state.ordNoteList && this.state.ordNoteList.map((item, index) => {
            ordNoteListtOption.push(<Option key={index} value={String(item.id)}>{item.descripts}</Option>)
        })

        // 登录科室
        let locOption = [];
        this.state.locList && this.state.locList.map((item, index) => {
            locOption.push(<Option key={index} value={String(item.id)} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })

        return <div className='usage-order-body' style={{ width: '100%', height: '100%', background: '#F5F7FE' }}>
            <div style={{ width: '25%', float: 'left', height: '100%' }}>
                <Card title='用法检索'>
                    <div>代码：<Input style={{ width: 200 }}
                        placeholder='请输入代码' onChange={Util.commonInputChange.bind(this, 'searchCode')}
                        onPressEnter={this.loadData.bind(this, '1', '', 'search')}
                    /></div>
                    <div style={{ marginTop: 10 }}>
                        描述：<Input style={{ width: 200 }} placeholder='请输入描述'
                            onChange={Util.commonInputChange.bind(this, 'descripts')}
                            onPressEnter={this.loadData.bind(this, '1', '', 'search')}
                        />
                        <Button type='primary' size='small' style={{ marginLeft: 10 }} onClick={this.loadData.bind(this, '1', '', 'search')}>查询</Button>
                    </div>
                </Card>
                <Card title='用法列表' style={{ marginTop: 10 }}>
                    <Table columns={this.columns} style={{ background: 'white', height: store.getState().tableHeight.y + 'px' }}
                        dataSource={this.state.dataSource}
                        onRow={this.onClickRow} bordered
                        rowClassName={this.setRowClassName}
                        rowKey={(data) => {
                            return data.id
                        }}
                        scroll={{ y: store.getState().tableHeight.y - 50 + 'px' }}

                        pagination={false}>
                    </Table>
                    <CommonPagination size={this.state.size} current={this.state.page} total={this.state.total}
                        search={this.state.search} pageSize={true}
                        onShowSizeChange={this.changePageSize.bind(this)} complete={false} dataSource={this.state.dataSource}
                        onChange={this.onChange.bind(this)} />
                </Card>
            </div>

            <div style={{ float: 'right', width: '74.5%', height: '100%' }}>
                <Card title='添加/修改用法关联医嘱配置'>
                    <Form>
                        <Col span={6}>
                            <FormItem {...formItemLayout} label='医院'>
                                {getFieldDecorator('hospID', {
                                    initialValue: this.state.hospID || this.state.userData.hospID,
                                    rules: [{ required: true, message: '请选择医院' }],
                                })(
                                    <Select placeholder='请选择医院' onChange={Util.handleSelectChange.bind(this, 'hospID')}
                                        showSearch allowClear
                                        filterOption={(input, option) =>
                                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            || option.props.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }>
                                        {hospitalOption}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>

                        <Col span={6}>
                            <FormItem {...formItemLayout} label='就诊类型'>
                                {getFieldDecorator('admTypeID', {
                                    initialValue: this.state.admTypeID,
                                    rules: [{ required: true, message: '请选择就诊类型' }],
                                })(
                                    <Select placeholder='请选择就诊类型' onChange={this.handleSelectLocTypeChange.bind(this, 'admTypeID')} allowClear>
                                        {admTypeOption}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>

                        <Col span={6}>
                            <FormItem {...formItemLayout} label='医嘱项'>
                                {getFieldDecorator('medID', {
                                    initialValue: this.state.medID,
                                    rules: [{ required: true, message: '请输入检索医嘱项' }],
                                })(
                                    <AutoComplete placeholder="输入内容检索" onChange={this.handleSelectChange.bind(this, 'findCode')}
                                        onSelect={this.handleSelectOption.bind(this, 'medID')}
                                        dataSource={ordNoteListtOption} />
                                )}
                            </FormItem>
                        </Col>

                        <Col span={6}>
                            <FormItem label='费用数量' {...formItemLayout}>
                                {getFieldDecorator('qty', {
                                    initialValue: this.state.qty,
                                    rules: [{ required: true, message: '请输入数量' }],
                                    getValueFromEvent: (event) => {
                                        return event.target.value.replace(/\D/g, '')
                                    },
                                })(
                                    <Input allowClear placeholder='请输入数量' />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6}>
                            <FormItem {...formItemLayout} label='开单科室'>
                                {getFieldDecorator('locID', {
                                    initialValue: this.state.locID,
                                    rules: [{ required: true, message: '请选择开单科室' }],
                                })(
                                    <Select showSearch allowClear optionFilterProp="seatchprop" placeholder='请选择开单科室' onChange={Util.handleSelectChange.bind(this, 'locID')}>
                                        {locOption}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6}>
                            <FormItem label='生效日期' {...formItemLayout}>
                                {getFieldDecorator('startDate', {
                                    initialValue: this.state.startDate ? moment(this.state.startDate, dayFormat) : '',
                                    rules: [{ required: true, message: '请选择生效日期' }],
                                })(
                                    <DatePicker placeholder='请选择生效日期' style={{ width: '100%' }} />
                                )}
                            </FormItem>
                        </Col>

                        <Col span={6}>
                            <FormItem label='失效日期' {...formItemLayout}>
                                {getFieldDecorator('stopDate', {
                                    initialValue: this.state.stopDate ? moment(this.state.stopDate, dayFormat) : '',
                                    // rules: [{ required: true, message: '请选择失效日期' }],
                                })(
                                    <DatePicker placeholder='请选择失效日期' style={{ width: '100%' }} />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={3}>
                            <FormItem label='自动计算费用' {...formItemCheck}>
                                {getFieldDecorator('autoFlag', {
                                    initialValue: this.state.autoFlag
                                })(
                                    <Checkbox checked={this.state.autoFlag} onChange={this.changeCommonCheckBox.bind(this, 'autoFlag')} />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={3}>
                            <Button type='primary' onClick={this.onSubmit.bind(this)}>保存</Button>
                            <Button style={{ marginLeft: 5 }} onClick={this.clearInput.bind(this)}>{!Util.isEmpty(this.state.rowID) ? '取消' : '清空'}</Button>
                        </Col>
                    </Form>
                </Card>

                <Card title='查询用法关联医嘱配置' style={{ marginTop: 10 }}>
                    <Table columns={this.rightColumns} style={{ background: 'white', height: store.getState().tableHeight.y - 30 + 'px' }}
                        dataSource={this.state.tableData}
                        onRow={this.onRightClickRow} bordered
                        rowClassName={this.setRowRightClassName}
                        rowKey={(data) => {
                            return data.id
                        }}
                        scroll={{ y: store.getState().tableHeight.y - 50 + 'px' }}

                        pagination={false}>
                    </Table>
                    <CommonPagination size={this.state.size} current={this.state.tablePage} total={this.state.tableTotal}
                        search={this.state.tableSearch} pageSize={true}
                        onShowSizeChange={this.changeRightPageSize.bind(this)} complete={true} dataSource={this.state.tableData}
                        onChange={this.onRightChange.bind(this)} />
                </Card>
            </div>
        </div>
    }

}

export default Form.create()(UsageRelatedOrdersPage);